package com.example.codequalityservice.controller;

import com.example.api.service.CodeQualityService;
import com.example.common.constant.Constants;
import com.example.common.constant.HttpHeaders;
import com.example.common.core.AjaxResult;
import com.example.common.entity.CodeQualityForPR;
import com.example.common.entity.CodeQualityResult;
import com.example.common.entity.PRInfo;
import com.example.common.entity.vo.CodeQualityVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DestinyCc
 * @date 2022/4/16
 */
@RestController
@RequestMapping("/quality")
public class CodeQualityController {

    @Reference
    CodeQualityService codeQualityService;

    @GetMapping("/calculate")
    public AjaxResult calculate(@RequestParam("owner") String owner,
                                @RequestParam("repo") String repo,
                                HttpServletRequest request){
        String appId = request.getHeader(HttpHeaders.APP_ID);
        String tenantId = request.getHeader(HttpHeaders.TENANT_ID);
        Long resultId = codeQualityService.calculateCodeQuality(appId, tenantId, owner, repo);
        Map<String, String> map = new HashMap<>();
        map.put("resultId", String.valueOf(resultId));
        return AjaxResult.success(map);
    }

    @GetMapping("/getResult")
    public AjaxResult getResult(@RequestParam("resultId") Long resultId,
                                HttpServletRequest request){
        CodeQualityResult codeQualityResult = codeQualityService.getCodeQualityResult(resultId, request.getHeader(HttpHeaders.TENANT_ID));
        if (codeQualityResult.getComplexity()==null){
            Map<String, String> map = new HashMap<>();
            map.put("resultId", String.valueOf(resultId));
            return AjaxResult.success(map);
        }
        CodeQualityVO codeQualityVO = new CodeQualityVO();
        BeanUtils.copyProperties(codeQualityResult, codeQualityVO);
        return AjaxResult.success(codeQualityVO);
    }

    @PostMapping("getPRCodeQuality")
    public AjaxResult getPRCodeQuality(@RequestBody PRInfo prInfo){
        String repoPath = Constants.DEFAULT_OUTPUT_DIR + prInfo.getRepo() + "/" + prInfo.getPullNumber();
        String remotePath = prInfo.getOwner() + "/" + prInfo.getRepo();
        File file = new File(repoPath);
        if (! file.exists()){
            codeQualityService.extractFiles(prInfo);
        }
        List<CodeQualityForPR> prCodeQuality = codeQualityService.getPRCodeQuality(repoPath, remotePath);
        return AjaxResult.success(prCodeQuality);
    }
}
